package com.example.shangjiba;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class HomeFragment extends Fragment {

    private TextView tvRecommendation;
    private SharedPreferences sharedPreferences;
    private BroadcastReceiver interestReceiver;
    
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private NewsAdapter newsAdapter;
    private HomeViewModel homeViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        tvRecommendation = view.findViewById(R.id.tv_recommendation);
        recyclerView = view.findViewById(R.id.recycler_view);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        
        sharedPreferences = requireActivity().getSharedPreferences("UserData", Context.MODE_PRIVATE);
        
        // 初始化RecyclerView
        initRecyclerView();
        
        // 初始化ViewModel
        initViewModel();
        
        // 初始化下拉刷新
        initSwipeRefresh();
        
        // 加载并显示兴趣推荐
        updateRecommendation();
        
        // 注册广播接收器，监听兴趣变化
        interestReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateRecommendation();
            }
        };
        
        IntentFilter filter = new IntentFilter("com.example.shangjiba.INTEREST_UPDATED");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            requireActivity().registerReceiver(interestReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            requireActivity().registerReceiver(interestReceiver, filter);
        }
        
        return view;
    }
    
    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        newsAdapter = new NewsAdapter();
        recyclerView.setAdapter(newsAdapter);
        
        // 设置列表项点击事件
        newsAdapter.setOnItemClickListener(newsItem -> {
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("news_item", newsItem);
            startActivity(intent);
        });
    }
    
    /**
     * 初始化ViewModel
     */
    private void initViewModel() {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        
        // 观察数据变化
        homeViewModel.getNewsListLiveData().observe(getViewLifecycleOwner(), newsList -> {
            newsAdapter.setNewsList(newsList);
            swipeRefreshLayout.setRefreshing(false);
        });
    }
    
    /**
     * 初始化下拉刷新
     */
    private void initSwipeRefresh() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            homeViewModel.refreshData();
        });
    }

    private void updateRecommendation() {
        String interest = sharedPreferences.getString("interest", "未选择");
        if (interest.isEmpty()) {
            interest = "未选择";
        }
        tvRecommendation.setText("根据您的兴趣【" + interest + "】，推荐内容如下");
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次回到前台时更新推荐内容
        updateRecommendation();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 注销广播接收器
        if (interestReceiver != null) {
            requireActivity().unregisterReceiver(interestReceiver);
        }
    }
}
